package rpc.remote.transport.netty.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;
import rpc.serialize.Serializer;

/**
 * @ClassName: NettyKryoEncoder
 * @Description: 自定义的编码器，转为字节
 * @author: Kowk
 * @since:1.0.0
 */
@AllArgsConstructor
public class NettyKryoEncoder extends MessageToByteEncoder<Object> {

    private final Serializer serializer;
    private final Class<?> genericClass;

    //将对象转为字节码在写入ByteBuf
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
     if(genericClass.isInstance(o)){
         //将对象转为byte
         byte[] body = serializer.serialize(o);
         //读取消息长度
         int dataLen = body.length;
         //写入消息对应的字节数组长度,writerIndex加4
         byteBuf.writeInt(dataLen);
         //写入字节内容
         byteBuf.writeBytes(body);
     }
    }
}
